﻿using System;
using System.Text;
using System.Threading;
using RabbitMQ.Client.Events;
using RabbitMQDemo.Common;

namespace RabbitMQDemo.Consumer
{
    public class Worker
    {
        private const string QueueName = "worker_queue";

        public static void Receive(string[] args)
        {
            var timeout = Utils.GetFirstValue(args);
            if (timeout == 0)
            {
                timeout = new Random().Next(1, 6);
            }
            Console.WriteLine($"timeout: {timeout}s");

            using var connection = MQClient.GetConnection();
            using var channel = connection.CreateModel();

            // 声明队列
            channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);

            /*
             * 设置限流策略
             *  prefetchSize: 消息的大小，如果设置为0则表示对消息的大小不限制
             *  prefetchCount: 告知RabbitMQ，在未收到消费端的消息确认时，不再分发消息，也就确保了当消费端处于忙碌状态时，不再分配任务
             *  global: 是否将该设置应用于整个通道
             */
            //channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                Console.WriteLine($"[Worker][{ea.DeliveryTag}]received：{message}");

                Thread.Sleep(timeout * 1000);
                //Task.Factory.StartNew(args =>
                //{
                //    Thread.Sleep(timeout * 1000);
                //    Console.WriteLine($"[Worker][{args}]done：{message}");
                //    channel.BasicAck(deliveryTag: (ulong)args, multiple: false);
                //}, ea.DeliveryTag);
            };

            channel.BasicConsume(queue: QueueName, autoAck: true, consumerTag: "testConsumer", noLocal: false, exclusive: false, arguments: null, consumer: consumer);

            Console.WriteLine("按任意键退出");
            Console.ReadKey();
        }
    }
}
